const Generator = require('yeoman-generator');
const glob = require('glob');
const ora = require('ora');
const { statSync } = require('fs');
const { basename } = require('path');

let loading = ora('fetching template......');
function noop() {
  return true;
}

class BasicGenerator extends Generator {
  constructor(opts) {
    super(opts);
    this.opts = opts;
    this.name = basename(opts.env.cwd);
  }

  isTsFile(f) {
    return f.endsWith('.ts') || f.endsWith('.tsx') || !!/(tsconfig\.json|tslint\.yml)/g.test(f);
  }

  writeFiles({ context, filterFiles = noop }) {
    loading.start();
    glob
      .sync('**/*', {
        cwd: this.templatePath(),
        dot: true,
      })
      .filter(file => !file.includes('node_modules'))
      .filter(filterFiles)
      .forEach(file => {
        const filePath = this.templatePath(file);
        if (statSync(filePath).isFile()) {
          if (file.split('/')[file.split('/').length-1].indexOf("_") == 0) {

            this.fs.copyTpl(
              this.templatePath(filePath),
              this.destinationPath(file.replace(/(.*)_/, '$1')),
              context,
            );
          } else {
            this.fs.copy(
              this.templatePath(filePath),
              this.destinationPath(file),
              context,
            );
          }
        }
      });
    loading.succeed();
  }

  prompt(questions) {
    // process.send && process.send({ type: 'prompt' });
    // process.emit('message', { type: 'prompt' });
    return super.prompt(questions);
  }
}

module.exports = BasicGenerator;
